package com.shuimin.group;

import com.shuimin.group.mid.chat.ChatEvent;
import com.shuimin.group.mid.chat.ChatService;
import com.shuimin.group.mid.redis.RedisKey;
import com.shuimin.group.mid.redis.RedisService;
import com.shuimin.group.mid.redis.RedisUtil;
import com.shuimin.group.model.weixin.WeixinUser;
import pond.common.JSON;
import pond.common.S;
import pond.common.STRING;
import pond.web.*;

import java.util.*;

public class WSCHAT extends Router {
    {
        get("/", InternalMids.websocket(
            wsctx -> {
                S.echo("-----------open date :" + new Date().toString());
                Session session = Session.get(wsctx);
                WeixinUser weixinUser = App.getLoginUser(wsctx);
                //用户上线
                //记录用户聊天消息发送通道，发送消息
                ChatService.add(session, wsctx);
                    /* 发送遗留聊天信息 */
                List<String> unreadkeys = RedisUtil.scanKey(new String("*" + weixinUser.id() + RedisKey.CHAT_MSG_UNREAD));
                Map<String, List<String>> unread = new HashMap<>();
                Map<String, List<Map<String, Object>>> unreadMsg = new HashMap<>();
                List<String> keys = new ArrayList<>();
                Map<String, Map<String, Object>> msgMap = RedisUtil.hscanMapFromKeys(keys);
                S._for(unreadkeys).each(key -> {
                    unread.put(key, RedisUtil.queryAllKeysFromStack(key));
                });
                S._for(unread).each(item -> {
                    List<String> msgList = item.getValue();
                    List<Map<String, Object>> groupMsgList = new ArrayList<>();
                    S._for(msgList).each(subItem -> {
                        groupMsgList.add(msgMap.get(subItem));
                    });
                    String group_id = item.getKey().split(":")[0];
                    S.echo("group_id :" + group_id);
                    unreadMsg.put(group_id, groupMsgList);
                });
                if (unreadMsg.size() > 0){
                    wsctx.sendTextFrame(JSON.stringify(unreadMsg));
                }
                wsctx.onMessage((msg, ctx) -> {
                    S.echo("======onmessage");
                    ChatEvent chatEvent = ChatEvent.message(msg, weixinUser);
                    if (null == chatEvent)
                    {
                        S.echo("not valid " + msg);
                        S.echo("not valid " + weixinUser);
                        // 消息不合法
                        return;
                    }
                    else
                    {
                        S.echo("======chatevent"+ chatEvent.toJSON());
                        //打开聊天室，发送遗留信息
                        //用户聊天
                        ChatService.handle(chatEvent);
                    }
                });

                wsctx.onClose(ctx -> {
                    ChatService.remove(Session.get(wsctx));
                    S.echo("-----------close date :"+ new Date().toString() );
                    //离开聊天室
                    //用户下线
                });
            })
        );
        get("/history", (req, resp) -> {
            String userId = App.getUserId(req);
            String groupId = req.param("group_id");
            if (STRING.isBlank(groupId))
            {
                resp.send(403," group id is null");
                return;
            }
            String msgId = req.param("message_id");
            String msg_key ="";

            if (STRING.notBlank(msgId)) {
                if (!RedisService.existMsgKey(msgId))
                {
                    resp.send(404, "message " + msgId + " not found");
                    return;
                }
            }

            String chatRecordKey = RedisService.getKey(groupId, userId, RedisKey.CHAT_RECORD);
            if (!RedisService.exist(chatRecordKey))
            {
                resp.send(404,"group "+ groupId + " not found");
                return;
            }
            // 没有参数，默认获取历史消息数量
            int msg_num = 10;
            String message_num = req.param("message_num");
            if (STRING.notBlank(message_num))
            {
                msg_num = Integer.valueOf(message_num);
            }
            List<String> keyList = RedisUtil.queryKeysFromStack(chatRecordKey, msg_num, msg_key);
            resp.render(Render.json(RedisUtil.hscanFromKeys(keyList)));
        });
    }
}
